package com.koron.common.web.qrcode.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.common.entity.EqCodeBean;
import com.koron.common.core.business.common.mapper.EqCodeBeanMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CommonUtils;
import com.koron.common.core.util.FilesUtil;
import com.koron.common.core.util.StringUtils;
import com.koron.common.web.feign.CarService;
import com.koron.common.web.feign.EquipmentService;
import com.koron.common.web.qrcode.bean.WxPageParameter;
import com.koron.common.web.qrcode.service.QRCodeService;
import com.koron.common.web.qrcode.utils.QRCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author twcao
 * @title: QRCodeController
 * @projectName GDH_EAM_V2
 * @description: 二维码
 * @date 2022/1/2510:06
 */
@Slf4j
@RestController
@RequestMapping("/qrCode")
@Api(tags = "二维码")
public class QRCodeController {

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    @Autowired
    private QRCodeService qrCodeService;

    @GetMapping("/create")
    @ApiOperation("根据内容生成二维码")
    @ApiImplicitParam(name = "preview", value = "是否预览, true: 预览，false=下载，默认为true", defaultValue = "true")
    public void createQRCode(@RequestParam(defaultValue = "200") int width,
                                          @RequestParam(defaultValue = "200") int height,
                                          @RequestParam String content,
                                          @RequestParam String fileName,
                                          @RequestParam(defaultValue = "png") String suffix,
                                          @RequestParam(defaultValue = "true") Boolean preview,
                                          HttpServletResponse response) {
        try(OutputStream os = response.getOutputStream()) {
            fileName = StringUtils.indexOf(fileName, ".") > -1 ? fileName : (fileName + ".png");
            if (!preview) {
                response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            byte[] qrCode = QRCodeUtils.createQRCode(width, height, content, suffix);
            os.write(qrCode);
        } catch (Exception e) {
            try (OutputStream os = response.getOutputStream()) {
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                os.write("附件下载失败".getBytes());
            } catch (Exception e1) {
                log.error(e.getMessage(), e1);
            }
        }
    }

    @GetMapping("/miniProgram/create/bk")
    @ApiOperation("根据内容生成小程序二维码bk")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preview", value = "是否预览, true: 预览，false=下载，默认为true", defaultValue = "true"),
            @ApiImplicitParam(name = "fileName", value = "文件名，下载时用，默认为scene的值")
    })
    public ResponseEntity<byte[]> createMiniProgramQRCodePlus(@RequestParam(defaultValue = "true") Boolean preview, String fileName, WxPageParameter parameter) {
        try {
            log.info("内容生成小程序二维码， parameter = {}", JSON.toJSONString(parameter));
            ResponseEntity<byte[]> entity = qrCodeService.createMiniProgramQRCode(parameter);
            HttpHeaders headers = entity.getHeaders();
            HttpHeaders header = new HttpHeaders();
            header.setConnection(headers.getConnection());
            header.setContentType(headers.getContentType());
            header.setCacheControl(headers.getCacheControl());
            header.setContentLength(headers.getContentLength());
            if(!preview) {
                if(StringUtils.isEmpty(fileName)) {
                    header.setContentDisposition(headers.getContentDisposition());
                } else {
                    header.setContentDispositionFormData("attachment", new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO-8859-1"));
                }
            }
            headers = header;
            return new ResponseEntity(entity.getBody(), headers, entity.getStatusCode());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Autowired
    private DefaultFastFileStorageClient storageClient;

    @Autowired
    private EquipmentService equipmentservice;

    @Autowired
    private CarService carservice;



    @GetMapping("/miniProgram/create")
    @ApiOperation("根据内容生成小程序二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "preview", value = "是否预览, true: 预览，false=下载，默认为true", defaultValue = "true"),
            @ApiImplicitParam(name = "fileName", value = "文件名，下载时用，默认为scene的值")
    })
    public ResponseEntity createMiniProgramQRCode(@RequestParam(defaultValue = "true") Boolean preview, String fileName, WxPageParameter parameter) {
        EqCodeBean eqCodeBean = ADOConnection.runTask(getCurrUser().getCurrDs(), factory -> {
            EqCodeBeanMapper mapper = factory.getMapper(EqCodeBeanMapper.class);
            EqCodeBean bean = mapper.queryByEquipmentIdAndEnvVersion(parameter.getScene(), parameter.getEnvVersion());
            return bean;
        }, EqCodeBean.class);

        // 没找到冗余台账，远程调用生成后，预览下载
        if(ObjectUtil.isNull(eqCodeBean)){
            if(parameter.getPage().equals("pages/equiLedger/equiDetail")){
                Response<EqCodeBean> response = equipmentservice.redundancyERcode(parameter.getScene(), parameter.getEqName(), parameter.getEnvVersion());
                eqCodeBean = CommonUtils.ok(response);
            }
            if(parameter.getPage().equals("pages/carManagement/carReady")){
                Response<EqCodeBean> response = carservice.redundancyERcode(parameter.getScene(), parameter.getEqName(), parameter.getEnvVersion());
                eqCodeBean = CommonUtils.ok(response);
            }
        }

        HttpHeaders header = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType(MediaType.IMAGE_JPEG_VALUE);
        header.setContentType(mediaType);
        header.setCacheControl("no-cache, must-revalidate");
        if (!preview) {
            MediaType mediaType2 = MediaType.parseMediaType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            header.setContentType(mediaType2);
            header.setContentDispositionFormData("attachment", eqCodeBean.getEquipmentId()+".jpg");
        }
        StorePath storePath = StorePath.parseFromUrl(eqCodeBean.getPath());
        ResponseEntity responseEntity = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), (DownloadCallback<ResponseEntity>) inputStream -> {
            byte[] bytes = new byte[0];
            try {
                bytes = FilesUtil.readStream(inputStream);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            header.setContentLength(bytes.length);
            log.info("字节大小 = " + bytes.length);
            return new ResponseEntity(bytes, header, HttpStatus.OK);
        });

        return responseEntity;
    }


}
